<template>
  <div class="form-box">
    <el-form
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-width="115px"
    >
      <el-form-item label="活动名称" prop="name">
        <el-input
          clearable
          placeholder="请输入活动名称"
          maxlength="20"
          show-word-limit
          style="width:35%"
          v-model="ruleForm.name"
          :disabled="isEdit"
        ></el-input>
      </el-form-item>
      <el-form-item label="活动档案" prop="activityArchives">
        <el-input
          clearable
          placeholder="请输入活动的目的和活动背景"
          maxlength="1000"
          type="textarea"
          :autosize="{ minRows: 4 }"
          show-word-limit
          style="width:35%"
          v-model.trim="ruleForm.activityArchives"
        ></el-input>
      </el-form-item>
      <el-form-item label="活动规则" prop="activityRule">
        <el-input
          clearable
          placeholder="请输入活动规则"
          maxlength="1000"
          type="textarea"
          :autosize="{ minRows: 4 }"
          show-word-limit
          style="width:35%"
          v-model.trim="ruleForm.activityRule"
        ></el-input>
      </el-form-item>
      <el-form-item label="活动预热时间" prop="preheatTime">
        <el-date-picker
          size="small"
          :disabled="isDisabled || isEdit"
          v-model="ruleForm.preheatTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="pickerOptions"
          @change="handlePreheatTime"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="活动起止时间" prop="activityTimeType">
        <el-radio-group v-model="ruleForm.activityTimeType" size="small">
          <el-radio
            v-for="item in activityTimeTypeList"
            :key="item.dictValue"
            :label="item.dictValue"
            >{{ item.dictLabel }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <!-- 短期 -->
      <el-form-item
        v-if="ruleForm.activityTimeType === 'SHORT_ACTIVITY' && !isEdit"
        prop="startEndTime"
      >
        <!-- <el-date-picker
          size="small"
          v-model="ruleForm.startEndTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="startEndTimeOptions"
          @change="handleStartEndTime"
        >
        </el-date-picker> -->
      </el-form-item>
      <el-form-item
        v-if="ruleForm.activityTimeType === 'SHORT_ACTIVITY' && isEdit"
        prop="startEndTime"
      >
        <el-date-picker
          v-model="ruleForm.startTime"
          :disabled="isEdit"
          type="datetime"
        >
        </el-date-picker
        >--
        <el-date-picker
          v-model="ruleForm.endTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="endTimeOptions"
        >
        </el-date-picker>
      </el-form-item>
      <!-- 长期 -->
      <el-form-item
        v-if="ruleForm.activityTimeType === 'LONG_ACTIVITY'"
        prop="startTime"
      >
        <el-select
          v-model="ruleForm.activityStartStatus"
          style="width:25%"
          clearable
        >
          <el-option
            v-for="item in activityStartStatusList"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"
          >
          </el-option>
        </el-select>
        <el-date-picker
          v-if="ruleForm.activityStartStatus === 'TIMING_START'"
          v-model="ruleForm.startTime"
          :disabled="isEdit"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择日期时间"
          :picker-options="startEndTimeOptions"
          popper-class="timing_picker"
          @change="handleStartTime"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="奖金提现时间" prop="awardTime">
        <el-date-picker
          size="small"
          v-model="ruleForm.awardTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="awardTimeOptions"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="入量配置" style="font-weight:600"> </el-form-item>
      <el-form-item
        label="展翅渠道"
        prop="inviteMatchingChannel.oneLevelChannelId"
      >
        <el-select
          v-model="ruleForm.inviteMatchingChannel.oneLevelChannelId"
          placeholder="请选择活动对应的一级渠道"
          style="width:35%"
          @change="selectOneLeve"
          clearable
          :disabled="isEdit"
        >
          <el-option
            v-for="item in introduceChannelList"
            :key="item.channelCode"
            :label="item.firstChannelName"
            :value="item.channelCode"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="inviteMatchingChannel.twoLevelChannelName">
        <el-input
          v-model="ruleForm.inviteMatchingChannel.twoLevelChannelName"
          placeholder="请输入对应的二级渠道名称"
          style="width:35%"
          clearable
          @input="channelNname"
          :disabled="isEdit"
        ></el-input>
        <p style="margin: -10px 0;">
          请您输入二级渠道名称前缀（例如新年活动-国画H5,就输入新年活动即可）
        </p>
        <div v-show="isShow">
          <i v-if="isShowIcon" class="el-icon-check verify-icon"></i>
          <i v-else class="el-icon-close verify-icon"></i>
        </div>
      </el-form-item>
      <el-form-item label="选择入量落地页" prop="landingPage">
        <el-select
          v-model="ruleForm.landingPage"
          placeholder="请选择活动对应的入量页面"
          style="width:35%"
          clearable
          :disabled="isEdit"
        >
          <el-option
            v-for="item in landingPageList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="handlerButton">
      <el-button type="info" @click="cancel">取 消</el-button>
      <el-button type="success" @click="handelTab('customConfig')">
        下一步
      </el-button>
    </div>
  </div>
</template>

<script>
import {
  getIntroduceChannel,
  channelVerify,
  landingPageName
} from '@/api/activityCenter/activityManage/common'
import _ from 'lodash'
import { sysNormalDisable } from '@utils/dictionariesFunc'
export default {
  props: ['activityInfo'],
  data() {
    let _this = this
    /* 起始时间校验 */
    var validateStartEndTime = (rule, value, callback) => {
      const { activityStartStatus, startTime } = this.ruleForm
      if (activityStartStatus === 'TIMING_START' && !startTime) {
        callback(new Error('请选择开始时间'))
      } else {
        callback()
      }
    }
    return {
      ruleForm: {
        name: '', //活动名称
        activityArchives: '', //活动档案
        activityRule: '', //活动规则
        preheatTime: [], //活动预热时间
        activityPreheatingStartTime: '', //预热开始时间
        activityPreheatingEndTime: '', //预热结束时间
        activityTimeType: 'SHORT_ACTIVITY', //活动时效
        startEndTime: [], //活动起始时间
        startTime: '', //活动开始时间
        endTime: '', //活动结束时间
        activityStartStatus: 'IMMEDIATELY_START', //活动开始状态
        awardTime: [], //领奖时间
        prizeWithdrawStartTime: '', //领奖开始时间
        prizeWithdrawEndTime: '', //领奖结束时间
        inviteMatchingChannel: {
          oneLevelChannelId: '', //一级渠道Id
          oneLevelChannelName: '', //一级渠道名称
          twoLevelChannelName: '' //二级渠道名称
        },
        landingPage: '' //入量落地页id
      },
      isDisabled: false, //禁用预热时间
      isEdit: false,
      introduceChannelList: [], //一级入量渠道
      landingPageList: [], //落地页
      isShow: false, //图标
      isShowIcon: true, //成功失败图标
      activityTimeTypeList: [], //活动时效
      activityStartStatusList: [], //活动开始状态
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
        }
      },
      startEndTimeOptions: {
        disabledDate(time) {
          if (!_this.ruleForm.activityPreheatingEndTime) {
            return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
          } else {
            return (
              time.getTime() <
              Date.parse(new Date(_this.ruleForm.activityPreheatingEndTime)) +
                24 * 60 * 60 * 1000
            )
          }
        }
      },
      awardTimeOptions: {
        disabledDate(time) {
          if (
            !_this.ruleForm.activityPreheatingEndTime &&
            !_this.ruleForm.startTime &&
            !_this.ruleForm.endTime
          ) {
            return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
          } else if (_this.ruleForm.endTime) {
            return (
              time.getTime() <
              Date.parse(new Date(_this.ruleForm.endTime)) + 24 * 60 * 60 * 1000
            )
          } else if (!_this.ruleForm.endTime) {
            if (_this.ruleForm.startTime) {
              return (
                time.getTime() <
                Date.parse(new Date(_this.ruleForm.startTime)) +
                  24 * 60 * 60 * 1000
              )
            } else if (_this.ruleForm.activityPreheatingEndTime) {
              return (
                time.getTime() <
                Date.parse(new Date(_this.ruleForm.activityPreheatingEndTime)) +
                  24 * 60 * 60 * 1000
              )
            }
          }
        }
      },
      endTimeOptions: {
        disabledDate(time) {
          return (
            time.getTime() <
            Date.parse(new Date(_this.ruleForm.startTime)) + 24 * 60 * 60 * 1000
          )
        }
      },
      rules: {
        name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
        activityArchives: [
          { required: true, message: '请输入活动档案', trigger: 'blur' }
        ],
        activityTimeType: [{ required: true, message: '请选择活动时效' }],
        startEndTime: [{ required: true, message: '请选择起始时间' }],
        startTime: [{ required: true, validator: validateStartEndTime }],
        awardTime: [
          { required: true, message: '请选择奖金提现时间', trigger: 'change' }
        ],
        'inviteMatchingChannel.oneLevelChannelId': [
          { required: true, message: '请选择展翅渠道', trigger: 'change' }
        ],
        'inviteMatchingChannel.twoLevelChannelName': [
          { required: true, message: '请选择二级渠道', trigger: 'blur' }
        ],
        landingPage: [
          { required: true, message: '请选择入量落地页', trigger: 'change' }
        ]
      }
    }
  },
  watch: {
    activityInfo: {
      handler(val) {
        if (val.activityStatus === 'ONGOING') {
          this.isEdit = true
        }
        this.$set(val, 'preheatTime', [
          val.activityPreheatingStartTime,
          val.activityPreheatingEndTime
        ])
        this.$set(val, 'startEndTime', [val.startTime, val.endTime])
        this.$set(val, 'awardTime', [
          val.prizeWithdrawStartTime,
          val.prizeWithdrawEndTime
        ])
        this.ruleForm = val
      }
    },
    startEndTimeOptions: {
      handler(val) {
        console.log('startEndTimeOptions', startEndTimeOptions)
      }
    }
  },
  async mounted() {
    /* 一级入量渠道 */
    getIntroduceChannel({}, (res) => {
      this.introduceChannelList = res
    })
    /* 落地页名称 */
    landingPageName({}, (res) => {
      this.landingPageList = res
    })
    /* 活动失效 */
    this.activityTimeTypeList = await sysNormalDisable(
      'activity_time_type',
      'activity_time_type'
    )
    /* 活动开始时间 */
    this.activityStartStatusList = await sysNormalDisable(
      'activity_invitation_status',
      'activity_invitation_status'
    )
  },
  methods: {
    /* 选择预热时间 */
    handlePreheatTime(val) {
      this.ruleForm.activityPreheatingStartTime = val ? val[0] : ''
      this.ruleForm.activityPreheatingEndTime = val ? val[1] : ''
      this.clearStartEndTime() //选择预热时间时 清空 起止时间
      this.clearAwardTime() //选择预热时间时 清空 提现时间
    },
    /* 短期起止时间 */
    handleStartEndTime(val) {
      this.ruleForm.startTime = val ? val[0] : ''
      this.ruleForm.endTime = val ? val[1] : ''
      this.clearAwardTime()
    },
    /* 长期定时开始时间 */
    handleStartTime(val) {
      console.log('handleStartTime', val)
      this.ruleForm.startTime = val ? val : ''
      this.clearAwardTime()
    },
    /* 清空起止时间 */
    clearStartEndTime() {
      this.ruleForm.startEndTime = []
      this.ruleForm.startTime = ''
      this.ruleForm.endTime = ''
    },
    /* 清空领奖时间 */
    clearAwardTime() {
      this.ruleForm.awardTime = []
      this.ruleForm.prizeWithdrawStartTime = ''
      this.ruleForm.prizeWithdrawEndTime = ''
    },
    /* 选择以及渠道，保存一级渠道名称 */
    selectOneLeve(val) {
      this.introduceChannelList.forEach((item) => {
        if (val === item.channelCode) {
          this.ruleForm.inviteMatchingChannel.oneLevelChannelName =
            item.firstChannelName
        }
      })
    },
    /* 校验二级渠道 */
    channelNname: _.debounce(function(val) {
      const { oneLevelChannelId } = this.ruleForm.inviteMatchingChannel
      const obj = { channelCode: oneLevelChannelId, secondChannelName: val }
      if (!oneLevelChannelId || !val) {
        this.isShow = false
      } else {
        channelVerify(obj, (res) => {
          this.isShow = true
          this.isShowIcon = res
        })
      }
    }, 500),
    /* 提交 */
    collectData() {
      const { activityTimeType, awardTime } = this.ruleForm
      this.ruleForm.prizeWithdrawStartTime = awardTime[0]
      this.ruleForm.prizeWithdrawEndTime = awardTime[1]
      let obj = Object.assign({}, this.ruleForm)
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          if (activityTimeType === 'SHORT_ACTIVITY') {
            obj.activityStartStatus = null
          }
          delete obj.preheatTime
          delete obj.startEndTime
          delete obj.awardTime
        } else {
          obj = { tab: 'generalConfig' }
        }
      })
      return obj
    },
    /* 下一步 */
    handelTab(name) {
      this.$emit('handleClick', { name })
    },
    /* 取消 */
    cancel() {
      this.$router.push({ name: 'wh:inviteHaveGift:activityList' })
    }
  }
}
</script>
<style lang="less">
.timing_picker .el-picker-panel__footer {
  display: none;
}
</style>
<style lang="less" scoped>
.verify-icon {
  position: absolute;
  top: 5px;
  left: 35%;
  font-size: 30px;
  margin-left: 10px;
}
.handlerButton {
  width: 190px;
  margin: 0 auto;
  .el-button {
    margin-right: 30px;
  }
}
</style>
